﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Nova_DAL;
using Nova_Common;
using Nova_MOD;
using System.Data.Common;
using System.Data;
using System.Text;
using System.Data.OleDb;
using System.Configuration;
using Newtonsoft.Json;

public partial class Manage_Code_List : System.Web.UI.Page
{
    Nova_DAL.DbHelper dbHelper = new DbHelper();
    Nova_DAL.DbHelper_ERP dbHelper_ERP = new DbHelper_ERP();
    ExcelToSQL ETSQL = new ExcelToSQL();
    string strSQL = "";
    DbCommand cmd = null;
    DataSet ds = null;
    public string strMaxStockNo = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.hidden.Value != "" && this.hidden.Value != "undefined")//判断是否是模态关闭后刷新页面
        {
            txt_StorageNo.Text = hidden.Value;
            gv_Bind();
            hidden.Value = "";
        }

        if (Session["StorageNov"] != null)
        {
            try
            {
                txt_StorageNo.Text = Session["StorageNov"].ToString();
                Session["StorageNov"] = null;
            }
            catch
            {
            }
            gv_Bind();
        }

        if (!IsPostBack)
        {
            // gv_Bind();
        }
    }

    public void gv_Bind()
    {
        strSQL = @"SELECT TAL.PID,TAL.StockNo,TBM.Mat_Code,TBM.MAT_NAME,TAL.Num,TAL.Act_Num,TBM.S01,TBM.TM01,TBM.S02,TBM.TM03,TAL.S05,
                        TBM.Unit_Base,TAL.TS01 FROM dbo.TAddStorage_List TAL 
                        LEFT JOIN dbo.TBase_Material TBM ON TBM.MAT_CODE=TAL.MAT_CODE
                        WHERE TAL.StockNo='" + txt_StorageNo.Text + "' ";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        gv.DataSource = dbHelper.ExecuteDataSet(cmd);
        gv.DataBind();
    }

    /// <summary>
    /// 新建入库订单
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ibtn_New_Click(object sender, ImageClickEventArgs e)
    {
        //lab_ERR.Text = "";
        if (Session["StorageNov"] != null)
        {
            Session["StorageNov"] = null;
        }

        txt_StorageNo.Text = getMaxStorageNo();
        gv_Bind();
    }


    /// <summary>
    ///得到最大的单据号
    /// </summary>
    protected string getMaxStorageNo()
    {
        strSQL = "Select max(SUBSTRING(StockNo,3,8)) as StockNo From TBill_AddStorage Where Left(StockNo,2) = 'EA'";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        ds = dbHelper.ExecuteDataSet(cmd);
        if (ds.Tables[0].Rows.Count > 0)
        {
            strMaxStockNo = ds.Tables[0].Rows[0]["StockNo"].ToString();
            if (strMaxStockNo == "")
            {
                strMaxStockNo = "EA00000001";
            }
            else
            {
                int iMaxStockNo = Convert.ToInt32(strMaxStockNo.ToString()) + 1;
                if (iMaxStockNo.ToString().Length == 1)
                {
                    strMaxStockNo = "EA0000000" + iMaxStockNo.ToString();
                }
                else if (iMaxStockNo.ToString().Length == 2)
                {
                    strMaxStockNo = "EA000000" + iMaxStockNo.ToString();
                }
                else if (iMaxStockNo.ToString().Length == 3)
                {
                    strMaxStockNo = "EA00000" + iMaxStockNo.ToString();
                }
                else if (iMaxStockNo.ToString().Length == 4)
                {
                    strMaxStockNo = "EA0000" + iMaxStockNo.ToString();
                }
                else if (iMaxStockNo.ToString().Length == 5)
                {
                    strMaxStockNo = "EA000" + iMaxStockNo.ToString();
                }
                else if (iMaxStockNo.ToString().Length == 6)
                {
                    strMaxStockNo = "EA00" + iMaxStockNo.ToString();
                }
                else if (iMaxStockNo.ToString().Length == 7)
                {
                    strMaxStockNo = "EA0" + iMaxStockNo.ToString();
                }
                else
                {
                    strMaxStockNo = "EA" + iMaxStockNo.ToString();
                }
            }
        }
        else
        {
            strMaxStockNo = "EA00000001";
        }
        return strMaxStockNo.ToString();
    }

    /// <summary>
    /// 添加入库单
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ibtn_Add_Click(object sender, ImageClickEventArgs e)
    {

        if (Session["StorageNov"] != null)
        {
            Session["StorageNov"] = null;
        }

        txt_StorageNo.Text = getMaxStorageNo();
        gv_Bind();

        //lab_ERR.Text = "";
        if (txt_StorageNo.Text.Trim() == "")
        {
            ShowBox.MessageBox(this.Page, "请输入订单号！");
            return;
        }
        strSQL = "Select StockNo From TBill_AddStorage where StockNo = '" + txt_StorageNo.Text + "'";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        ds = dbHelper.ExecuteDataSet(cmd);
        if (ds.Tables[0].Rows.Count > 0)
        {
            ShowBox.MessageBox(this.Page, "已有订单号！");
            return;
        }
        else
        {

            //strSQL = "INSERT INTO TBill_AddStorage(StockNo,Small_BillType,Contents,Bill_Status,OID) values('" + txt_StorageNo.Text.Trim() + "','11','" + txt_Contents.Text.Trim() + "','0','" + Request.Cookies["vNovaUserNo"].Value.ToString() + "')";
            //xgw 修改
            string Small_BillType = "11";
            strSQL = "INSERT INTO TBill_AddStorage(StockNo,Small_BillType,Contents,Bill_Status,OID,B01) values('" + txt_StorageNo.Text.Trim() + "','" + Small_BillType + "','" + txt_Contents.Text.Trim() + "','0','" + Request.Cookies["vNovaUserNo"].Value.ToString() + "',0)";
            cmd = dbHelper.GetSqlStringCommond(strSQL);
            int i = dbHelper.ExecuteNonQuery(cmd);
            if (i > 0)
            {
                ShowBox.MessageBox(this.Page, "添加成功！");
                return;
            }
            else
            {
                ShowBox.MessageBox(this.Page, "添加失败！");
                return;
            }
        }
    }
    /// <summary>
    /// 查询
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ibtn_Search_Click(object sender, ImageClickEventArgs e)
    {
        //lab_ERR.Text = "";
        if (txt_StorageNo.Text == "")
        {
            ShowBox.MessageBox(this.Page, "请输入订单号！");
            return;
        }
        gv_Bind();
    }

    /// <summary>
    /// gv 修改
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ibtn_Edit_Click(object sender, ImageClickEventArgs e)
    {
        Session["StorageNov"] = txt_StorageNo.Text;
        Random rnd = new Random();
        DateTime dtime = new DateTime();
        string stime = dtime.Date.ToString("yyyymmss") + rnd.Next(10000).ToString();

        ImageButton ibtnE = (ImageButton)sender;
        string[] sArray = ibtnE.CommandArgument.ToString().Split('|');
        //Page.ClientScript.RegisterStartupScript(GetType(), "info", "<script language='javascript'>document.getElementById('hidden').value=window.showModalDialog('Code_Edit.aspx?Romands=" + stime + "&MType=Edit&PID=" + sArray[0].ToString() + "&StorageNo=" + sArray[1].ToString() + "', window, 'dialogWidth=600px;dialogHeight=180px;scroll:no;resizable:no;status:0;');document.URL=location.href;</script>)");
         ClientScript.RegisterStartupScript(GetType(), "info", "<script language='javascript'>document.getElementById('hidden').value=window.open('Code_Edit.aspx?Romands=" + stime + "&MType=Edit&PID=" + sArray[0].ToString() + "&StorageNo=" + sArray[1].ToString() + "', window, 'Height=220px,Width=600px,top=300, left=500, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no');document.URL=location.href;</script>)");

    }

    /// <summary>
    /// gv 删除
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ibtn_Delete_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton ibtnE = (ImageButton)sender;
        strSQL = "DELETE FROM TAddStorage_List WHERE PID = '" + ibtnE.CommandArgument.ToString() + "'";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        int i = dbHelper.ExecuteNonQuery(cmd);
        if (i > 0)
        {
            ShowBox.MessageBox(this.Page, "删除成功！");
            gv_Bind();
            return;
        }
        else
        {
            ShowBox.MessageBox(this.Page, "删除失败！");
            return;
        }
    }

    //protected void ibtn_DR_Click(object sender, ImageClickEventArgs e)
    //{

    //}

    private void DataSetToSql(DataSet ds)
    {
        DataTable dt = ds.Tables[0];
        DateTime time = System.DateTime.Now;
        if (Convert.ToString(dt.Columns[0]) != "验收入库单")
        {
            ShowBox.MessageBox(this.Page, "请先下载Excel模版，填写数据后在汇入！！");
            return;
        }
        StringBuilder sbMsg = new StringBuilder();
        if (string.IsNullOrEmpty(dt.Rows[0][6].ToString()))
        {
            sbMsg.Append("预收单号必须填写！");
        }
        else if (CheckExistStockNo(dt.Rows[0][6].ToString().Trim()))
        {
            sbMsg.Append("领料单号已经存在！");
        }


        for (int i = 2; i < dt.Rows.Count; i++)
        {
            decimal d = 0;
            try
            {
                d = Convert.ToDecimal(dt.Rows[i][0].ToString());
            }
            catch
            {
                d = 0;
                sbMsg.Append("序号必须为数字！");
            }

            if (string.IsNullOrEmpty(dt.Rows[i][1].ToString()))
            {
                sbMsg.Append("序号 " + d.ToString() + "：采购批号必须填写！");
            }
            if (string.IsNullOrEmpty(dt.Rows[i][2].ToString()))
            {
                sbMsg.Append("序号 " + d.ToString() + "：物料代号必须填写！");
            }
            if (dt.Rows[i][3].ToString().Split('/').Length < 2)
            {
                sbMsg.Append("序号 " + d.ToString() + "：名称与规格之间要加反斜杠 ！");
            }
            try
            {
                decimal a = Convert.ToDecimal(dt.Rows[i][6].ToString());
            }
            catch
            {
                sbMsg.Append("序号 " + d.ToString() + "：入库数量必须为数字！");
            }

            if (sbMsg.Length > 0)
            {
                break;
            }

        }
        if (sbMsg.Length > 0)
        {
            ShowBox.MessageBox(this.Page, sbMsg.ToString());
            return;
        }

        HttpCookie WCode = Request.Cookies["WCode"];
        HttpCookie WName = Request.Cookies["WName"];

        strSQL = "INSERT INTO TBill_AddStorage(StockNo,Small_BillType,Contents,Bill_Status,OID,S01,S02) values('" + dt.Rows[0][6].ToString() + "','11','','0','" + Request.Cookies["vNovaUserNo"].Value.ToString() + "','" + dt.Rows[0][2].ToString() + "','" + dt.Rows[0][4].ToString() + "')";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        dbHelper.ExecuteNonQuery(cmd);

        string strErr = "物料编码为：";
        int iFlag_Count = 0;
        for (int i = 2; i < dt.Rows.Count; i++)
        {
            //如果物料不在立体仓库的物料资料中，则提示 并且不添加数据
            if (iCheckMaterail(dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString()) == 0)
            {
                iFlag_Count = 1;
                strErr += dt.Rows[i][2].ToString() + "  ";
            }
            else
            {
                string MatName = string.Empty;
                string S01 = string.Empty;
                if (!string.IsNullOrEmpty(dt.Rows[i][3].ToString()))
                {
                    MatName = dt.Rows[i][3].ToString().Split('/')[0];
                    S01 = dt.Rows[i][3].ToString().Substring(MatName.Length + 1);
                }

                string strSec_Mat_ID = getSec_Mat_ID(dt.Rows[i][2].ToString(), Request.Cookies["vNovaUserNo"].Value.ToString(), WCode.Value.ToString().Trim(), HttpUtility.UrlDecode(WName.Value.ToString().Trim()));
                int iCount = CheckInfo(dt.Rows[0][6].ToString(), dt.Rows[i][2].ToString(), strSec_Mat_ID);
                if (iCount > 0)
                {
                    strSQL = @"UPDATE TAddStorage_List SET Num=Num+'" + Convert.ToDecimal(dt.Rows[i][6].ToString()) + "' WHERE PID='" + iCount + "'";
                }
                else
                {
                    strSQL = @"Insert into TAddStorage_List(StockNo,Mat_Code,Num,Act_Num,Sec_Mat_ID,DynamicState01,DynamicState02,DynamicState03,DynamicState04,DynamicState05,TS01,
TS02,TS03,TS04,TS05,S01,S02,S03,S04,S05,S06,S07,S08,S09,S10,S11,S12,S13,S14,S15,S16,S17,S18,S19,S20,
V01,V02,V03,V04,V05,V06,V07,V08,V09,V10,VN01,VN02,VN03,VN04,VN05,Add_Flag1,Add_Flag2,Add_Flag3,Add_Flag4) values(@StockNo,@Mat_Code,@Num,@Act_Num,@Sec_Mat_ID,@DynamicState01,@DynamicState02,@DynamicState03,@DynamicState04,@DynamicState05,@TS01,
@TS02,@TS03,@TS04,@TS05,@S01,@S02,@S03,@S04,@S05,@S06,@S07,@S08,@S09,@S10,@S11,@S12,@S13,@S14,@S15,@S16,@S17,@S18,@S19,@S20,
@V01,@V02,@V03,@V04,@V05,@V06,@V07,@V08,@V09,@V10,@VN01,@VN02,@VN03,@VN04,@VN05,@Add_Flag1,@Add_Flag2,@Add_Flag3,@Add_Flag4)";
                }

                cmd = dbHelper.GetSqlStringCommond(strSQL);
                dbHelper.AddInParameter(cmd, "@StockNo", DbType.String, dt.Rows[0][6].ToString());
                dbHelper.AddInParameter(cmd, "@Mat_Code", DbType.String, dt.Rows[i][2].ToString());
                dbHelper.AddInParameter(cmd, "@Num", DbType.Decimal, Convert.ToDecimal(dt.Rows[i][6].ToString()));
                dbHelper.AddInParameter(cmd, "@Act_Num", DbType.Decimal, 0);
                dbHelper.AddInParameter(cmd, "@Sec_Mat_ID", DbType.String, strSec_Mat_ID);
                dbHelper.AddInParameter(cmd, "@DynamicState01", DbType.Int16, 0);
                dbHelper.AddInParameter(cmd, "@DynamicState02", DbType.Int16, 0);
                dbHelper.AddInParameter(cmd, "@DynamicState03", DbType.Int16, 0);
                dbHelper.AddInParameter(cmd, "@DynamicState04", DbType.Int16, 0);
                dbHelper.AddInParameter(cmd, "@DynamicState05", DbType.Int16, 0);
                dbHelper.AddInParameter(cmd, "@TS01", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@TS02", DbType.String, WCode.Value.ToString().Trim());
                dbHelper.AddInParameter(cmd, "@TS03", DbType.String, HttpUtility.UrlDecode(WName.Value.ToString().Trim()));
                dbHelper.AddInParameter(cmd, "@TS04", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@TS05", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S01", DbType.String, S01);
                dbHelper.AddInParameter(cmd, "@S02", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S03", DbType.String, dt.Rows[i][1].ToString());
                dbHelper.AddInParameter(cmd, "@S04", DbType.String, dt.Rows[i][5].ToString());
                dbHelper.AddInParameter(cmd, "@S05", DbType.String, dt.Rows[i][7].ToString());
                dbHelper.AddInParameter(cmd, "@S06", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S07", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S08", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S09", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S10", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S11", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S12", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S13", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S14", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S15", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S16", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S17", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S18", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S19", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@S20", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@V01", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@V02", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@V03", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@V04", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@V05", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@V06", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@V07", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@V08", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@V09", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@V10", DbType.String, "");
                dbHelper.AddInParameter(cmd, "@VN01", DbType.Decimal, 0);
                dbHelper.AddInParameter(cmd, "@VN02", DbType.Decimal, 0);
                dbHelper.AddInParameter(cmd, "@VN03", DbType.Decimal, 0);
                dbHelper.AddInParameter(cmd, "@VN04", DbType.Decimal, 0);
                dbHelper.AddInParameter(cmd, "@VN05", DbType.Decimal, 0);
                dbHelper.AddInParameter(cmd, "@Add_Flag1", DbType.Int16, 0);
                dbHelper.AddInParameter(cmd, "@Add_Flag2", DbType.Int16, 0);
                dbHelper.AddInParameter(cmd, "@Add_Flag3", DbType.Int16, 0);
                dbHelper.AddInParameter(cmd, "@Add_Flag4", DbType.Int16, 0);
                dbHelper.ExecuteNonQuery(cmd);
            }


        }
        if (iFlag_Count == 1)
        {
            strErr += "不存在立体库中。";
            //lab_ERR.Text = strErr.ToString();

            strSQL = "DELETE TBill_AddStorage WHERE STOCKNO NOT IN(SELECT STOCKNO FROM TAddStorage_List) AND STOCKNO='" + dt.Rows[0][6].ToString() + "'";
            cmd = dbHelper.GetSqlStringCommond(strSQL);
            dbHelper.ExecuteNonQuery(cmd);
        }


    }

    private void CheckMaterail(string MatCode, string MatNameAndS01)
    {
        //查看物料表中是否存在该物料
        strSQL = "SELECT COUNT(MAT_CODE) FROM TBase_Material WHERE MAT_CODE='" + MatCode + "' ";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        DataSet ds_info = dbHelper.ExecuteDataSet(cmd);
        if (ds_info.Tables[0].Rows[0][0].ToString() == "0")
        {
            string MatName = string.Empty;
            string S01 = string.Empty;
            if (!string.IsNullOrEmpty(MatNameAndS01))
            {
                MatName = MatNameAndS01.Split('/')[0];
                S01 = MatNameAndS01.Substring(MatName.Length + 1);
            }

            strSQL = "INSERT INTO TBase_Material(MAT_CODE,MAT_NAME,S01) values('" + MatCode + "','" + MatName + "','" + S01 + "')";
            cmd = dbHelper.GetSqlStringCommond(strSQL);
            dbHelper.ExecuteNonQuery(cmd);
        }
    }


    private int iCheckMaterail(string MatCode, string MatNameAndS01)
    {
        int iCount = 0;
        //查看物料表中是否存在该物料
        strSQL = "SELECT COUNT(MAT_CODE) FROM TBase_Material WHERE MAT_CODE='" + MatCode.Trim() + "' ";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        DataSet ds_info = dbHelper.ExecuteDataSet(cmd);

        iCount = Convert.ToInt32(ds_info.Tables[0].Rows[0][0].ToString());
        return iCount;
    }

    private bool CheckExistStockNo(string StockNo)
    {
        strSQL = @"select count(1) from dbo.TBill_AddStorage where StockNo= '" + StockNo + "'";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        return Convert.ToInt32(dbHelper.ExecuteScalar(cmd)) > 0 ? true : false;
    }


    /// <summary>
    /// 判断是否添加过明细
    /// </summary>
    /// <param name="strSec_Mat_ID"></param>
    /// <returns></returns>
    protected int CheckInfo(string strStroageNo, string Mat_Code, string strSec_Mat_ID)
    {
        strSQL = @"SELECT PID FROM TAddStorage_List WHERE StockNo=@StockNo AND Mat_Code=@Mat_Code AND Sec_Mat_ID=@Sec_Mat_ID";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        dbHelper.AddInParameter(cmd, "@StockNo", DbType.String, strStroageNo);
        dbHelper.AddInParameter(cmd, "@Mat_Code", DbType.String, Mat_Code);
        dbHelper.AddInParameter(cmd, "@Sec_Mat_ID", DbType.String, strSec_Mat_ID);
        DataSet ds_TAL = dbHelper.ExecuteDataSet(cmd);
        if (ds_TAL != null && ds_TAL.Tables[0].Rows.Count > 0)
        {
            return Convert.ToInt32(ds_TAL.Tables[0].Rows[0][0].ToString());
        }
        else
        {
            return 0;
        }
    }

    /// <summary>
    /// 生成二级编码
    /// </summary>
    /// <param name="i"></param>
    /// <returns></returns>
    protected string getSec_Mat_ID(string strMat_Code, string strUserName, string strWCode, string strWName)
    {
        cmd = dbHelper.GetStoredProcCommond("SP_Get_Sec_Mat_ID");
        dbHelper.AddInParameter(cmd, "@Mat_Code", DbType.String, strMat_Code);
        dbHelper.AddInParameter(cmd, "@D01", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@D02", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@D03", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@D04", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@D05", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@D06", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@D07", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@D08", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@D09", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@D10", DbType.String, "");
        //dbHelper.AddInParameter(cmd, "@S01", DbType.String, strWCode.Trim());
        //dbHelper.AddInParameter(cmd, "@S02", DbType.String, strWName.Trim());
        dbHelper.AddInParameter(cmd, "@S01", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S02", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S03", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S04", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S05", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S06", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S07", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S08", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S09", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S10", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S11", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S12", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S13", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S14", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S15", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S16", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S17", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S18", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S19", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@S20", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@N01", DbType.Decimal, 0);
        dbHelper.AddInParameter(cmd, "@N02", DbType.Decimal, 0);
        dbHelper.AddInParameter(cmd, "@N03", DbType.Decimal, 0);
        dbHelper.AddInParameter(cmd, "@N04", DbType.Decimal, 0);
        dbHelper.AddInParameter(cmd, "@N05", DbType.Decimal, 0);
        dbHelper.AddInParameter(cmd, "@N06", DbType.Decimal, 0);
        dbHelper.AddInParameter(cmd, "@N07", DbType.Decimal, 0);
        dbHelper.AddInParameter(cmd, "@N08", DbType.Decimal, 0);
        dbHelper.AddInParameter(cmd, "@N09", DbType.Decimal, 0);
        dbHelper.AddInParameter(cmd, "@N10", DbType.Decimal, 0);
        dbHelper.AddInParameter(cmd, "@DynamicState01", DbType.Int16, 0);
        dbHelper.AddInParameter(cmd, "@DynamicState02", DbType.Int16, 0);
        dbHelper.AddInParameter(cmd, "@DynamicState03", DbType.Int16, 0);
        dbHelper.AddInParameter(cmd, "@DynamicState04", DbType.Int16, 0);
        dbHelper.AddInParameter(cmd, "@DynamicState05", DbType.Int16, 0);
        dbHelper.AddInParameter(cmd, "@TS01", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@TS02", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@TS03", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@TS04", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@TS05", DbType.String, "");
        dbHelper.AddInParameter(cmd, "@ForceNew", DbType.Int16, 1);
        dbHelper.AddInParameter(cmd, "@UserName", DbType.String, strUserName);
        dbHelper.AddOutParameter(cmd, "@Sec_Mat_ID", DbType.Int32, 20);
        dbHelper.AddOutParameter(cmd, "@ResNO", DbType.Int16, 10);
        dbHelper.AddOutParameter(cmd, "@ResMsg", DbType.String, 255);
        dbHelper.ExecuteNonQuery(cmd);
        int iSecs = Convert.ToInt32(dbHelper.GetParameter(cmd, "@Sec_Mat_ID").Value.ToString());
        string strSecs = iSecs.ToString();
        return strSecs;
    }

    protected void ibtn_ERP_Click(object sender, ImageClickEventArgs e)
    {

        //lab_ERR.Text = "";
        int iCount = 0;
        int iFlag = 0;


        strSQL = @"SELECT ID FROM TB_OrgCode";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        DataSet ds_OrgCode = dbHelper.ExecuteDataSet(cmd);


        strSQL = @"SELECT DocID,OrgCode,DocDate,DocT,DocTypeCode,DocTypeName,NowTime,ExcuteState,DocNo,MoCode,BZ 
                        FROM ERP_WMS_CRK WHERE DocT='入库' AND ExcuteState=0 AND OrgCode='" + ds_OrgCode.Tables[0].Rows[0][0].ToString() + "'";
        cmd = dbHelper_ERP.GetSqlStringCommond(strSQL);
        ds = dbHelper_ERP.ExecuteDataSet(cmd);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            string strErr = "";

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {

                using (Trans t = new Trans())
                {
                    try
                    {
                        //主表
                        iCount = Bind_ERP(t, ds.Tables[0].Rows[i]["DocNo"].ToString().Trim(), ds.Tables[0].Rows[i]["BZ"].ToString().Trim());


                        strSQL = @"SELECT ZBJLH,WZBH,WLMC,WLGG,TXM,PH,SCRQ,SL,BZ,WareHsCode,WareHsName FROM dbo.ERP_WMS_CRK2 WHERE ZBJLH='" + ds.Tables[0].Rows[i]["DocID"].ToString().Trim() + "'";
                        cmd = dbHelper_ERP.GetSqlStringCommond(strSQL);
                        DataSet ds_Info = dbHelper_ERP.ExecuteDataSet(cmd);

                        for (int j = 0; j < ds_Info.Tables[0].Rows.Count; j++)
                        {
                            string str = ds_Info.Tables[0].Rows[j]["wlmc"].ToString().Trim() + "/" + ds_Info.Tables[0].Rows[j]["wlgg"].ToString().Trim();
                            CheckMaterail(ds_Info.Tables[0].Rows[j]["wzbh"].ToString().Trim(), str);

                            string strSec_Mat_ID = getSec_Mat_ID(ds_Info.Tables[0].Rows[j]["wzbh"].ToString().Trim(), Request.Cookies["vNovaUserNo"].Value.ToString(), ds_Info.Tables[0].Rows[j]["WareHsCode"].ToString().Trim(), ds_Info.Tables[0].Rows[j]["WareHsName"].ToString().Trim());
                            //明细
                            Bind_ERP_Info(iCount, t, ds.Tables[0].Rows[i]["DocNo"].ToString().Trim(), ds_Info.Tables[0].Rows[j]["wzbh"].ToString().Trim(), Convert.ToDecimal(ds_Info.Tables[0].Rows[j]["SL"].ToString().Trim()), strSec_Mat_ID, ds_Info.Tables[0].Rows[j]["WareHsCode"].ToString().Trim(), ds_Info.Tables[0].Rows[j]["WareHsName"].ToString().Trim());
                            iFlag = 1;
                        }

                        t.Commit();
                    }
                    catch (Exception ex)
                    {
                        strErr = ex.Message.ToString();
                        iFlag = 0;
                        t.RollBack();
                    }

                    strErr = strErr.Replace("'", " ");
                    //反馈
                    strSQL = @"UPDATE ERP_WMS_CRK SET ExcuteState='" + iFlag + "',fksj='" + DateTime.Now.ToString() + "',bz='" + strErr + "' WHERE DocID='" + ds.Tables[0].Rows[i]["DocID"].ToString().Trim() + "'";
                    cmd = dbHelper_ERP.GetSqlStringCommond(strSQL);
                    dbHelper_ERP.ExecuteNonQuery(cmd);

                }
            }
        }
        else
        {
            ShowBox.MessageBox(this.Page, "没有数据！");
            return;
        }

        if (iFlag == 1)
        {
            ShowBox.MessageBox(this.Page, "导入成功！");
            return;
        }
        else
        {
            ShowBox.MessageBox(this.Page, "导入失败！");
            return;
        }

    }


    protected int Bind_ERP(Trans t, string strStockNo, string strContents)
    {
        int iCount = 0;
        strSQL = "Select StockNo From TBill_AddStorage where StockNo = '" + strStockNo.Trim() + "'";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        DataSet ds_Add = dbHelper.ExecuteDataSet(cmd);
        if (ds_Add.Tables[0].Rows.Count > 0)
        {
            iCount = -1;//订单编号存在
        }
        else
        {
            strSQL = "INSERT INTO TBill_AddStorage(StockNo,Small_BillType,Contents,Bill_Status,OID) values('" + strStockNo + "','11','" + strContents + "','0','" + Request.Cookies["vNovaUserNo"].Value.ToString() + "')";
            cmd = dbHelper.GetSqlStringCommond(strSQL);
            if (t == null)
            {
                dbHelper.ExecuteNonQuery(cmd);
            }
            else
            {
                dbHelper.ExecuteNonQuery(cmd, t);
            }
        }
        return iCount;
    }

    public void Bind_ERP_Info(int iCount, Trans t, string strStockNo, string strMat_Code, decimal dNum, string strSec_Mat_ID, string strWCode, string WName)
    {

        strSQL = @"Insert into TAddStorage_List(StockNo,Mat_Code,Num,Act_Num,Sec_Mat_ID,TS02,TS03) 
                                    values('" + strStockNo + "','" + strMat_Code + "','" + dNum + "',0,'" + strSec_Mat_ID + "','" + strWCode.Trim() + "','" + WName.Trim() + "')";

        cmd = dbHelper.GetSqlStringCommond(strSQL);
        if (t == null)
        {
            dbHelper.ExecuteNonQuery(cmd);
        }
        else
        {
            dbHelper.ExecuteNonQuery(cmd, t);
        }
    }


    protected void lbrn_Text_Click(object sender, EventArgs e)
    {
        try
        {
            strSQL = @"SELECT COUNT(1) FROM ERP_WMS_CRK";
            cmd = dbHelper_ERP.GetSqlStringCommond(strSQL);
            dbHelper_ERP.ExecuteNonQuery(cmd);
            ShowBox.MessageBox(this.Page, "连接成功！");
            return;
        }
        catch (Exception ex)
        {
            ShowBox.MessageBox(this.Page, "连接失败！");
            return;
        }
    }

    //protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    //{
    //if (e.Row.RowType == DataControlRowType.DataRow)
    //{
    //    Session["StorageNov"] = txt_StorageNo.Text;
    //    Random rnd = new Random();
    //    DateTime dtime = new DateTime();
    //    string stime = dtime.Date.ToString("yyyymmss") + rnd.Next(10000).ToString();

    //    ImageButton ibtnE = (ImageButton)e.Row.FindControl("ibtn_Edit");
    //    string[] sArray = ibtnE.CommandArgument.ToString().Split('|');
    //    string updateUrl = "document.getElementById('hidden').value=window.showModalDialog('Code_Edit.aspx?Romands=" + stime + "&MType=Edit&PID=" + sArray[0].ToString() + "&StorageNo=" + sArray[1].ToString() + "', window, 'dialogWidth=600px;dialogHeight=180px;scroll:no;resizable:no;status:0;');document.URL=location.href;";
    //    ibtnE.Attributes.Add("onclick", updateUrl);
    //}       
    // }
}
